/*
 * Copyright 2007 Matt Jensen
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
 * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 */
package org.jtell.spring;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jtell.EventChannel;
import org.jtell.internal.Guard;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * <p>
 * <code>ListenerRegisteringBeanPostProcessor</code> is an implementation of the Spring {@link BeanPostProcessor}
 * interface which registers all beans in the Spring application context with an associated event channel.
 * </p>
 * <p>
 * <strong>Thread Safety</strong><br/>
 * Instances of this class are safe for multithreaded access.
 * </p>
 */
public class ListenerRegisteringBeanPostProcessor implements BeanPostProcessor
{
    private static Log LOG = LogFactory.getLog(ListenerRegisteringBeanPostProcessor.class);

    /**
     * <p>
     * The event channel with which listeners are to be registered.
     * </p>
     */
    private final EventChannel m_eventChannel;

    /**
     * <p>
     * Construct a {@link ListenerRegisteringBeanPostProcessor} instance.
     * </p>
     *
     * @param eventChannel the event channel with which listeners are to be registered.
     */
    public ListenerRegisteringBeanPostProcessor(final EventChannel eventChannel)
    {
        super();
        Guard.notNull("eventChannel", eventChannel);

        m_eventChannel = eventChannel;
    }

    /* inherit javadoc */
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException
    {
        return bean;
    }

    /* inherit javadoc */
    public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException
    {
        if (LOG.isDebugEnabled())
        {
            LOG.debug(String.format(
                    "Registering bean %s@%d with event channel [%s], defined under name [%s] in the application context.",
                    bean.getClass(), System.identityHashCode(bean), m_eventChannel, beanName));
        }
        m_eventChannel.registerListener(bean);
        return bean;
    }
}
